#/bin/bash

sids=($*)
dst=${sids[0]}

title="update $*"

#
# 检查目标服务器的配置
#
dst_merged=`./mysql/query_valid_server_field.sh $dst merged`
if [ -z "$dst_merged" ]; then
    ./util/error.sh "$title" "dst invalid"
    exit 1
fi

dst_old_db_name=`./config/game_db_name.sh $dst`
if [ -z $dst_old_db_name ]; then
    ./util/error.sh "$title" "dst old db name invalid"
    exit 1
fi

dst_db_address=`./config/game_db_address.sh $dst`
if [ -z $dst_db_address ]; then
    ./util/error.sh "$title" "dst db address invalid"
    exit 1
fi

dst_url=`./mysql/query_valid_server_field.sh $dst host`
if [ -z $dst_url ]; then
    ./util/error.sh "$title" "dst url invalid"
    exit 1
fi

#
# 更新合服后的目标数据库
#
if [ $dst_merged -eq 0 ]; then
    dst_new_db_name=`./config/game_db_name.sh $dst $dst`
    if [ -z $dst_new_db_name ]; then
        ./util/error.sh "$title" "dst new db name invalid"
        exit 1
    fi
    
    echo "copy $dst_db_address/$dst_old_db_name to $dst_db_address/$dst_new_db_name ..."
    mongo --host $dst_db_address --eval "db.copyDatabase('$dst_old_db_name', '$dst_new_db_name')"
    if (($? != 0)); then
        ./util/error.sh "$title" "copy db failed"
        exit 1
    fi

    # 修改目标服的config.js中的数据库名称
    dst_host_ip=`./config/get.sh server.query game $dst ip`
    dst_path=`./config/get.sh game.path $dst`
    ssh $dst_host_ip "source ~/.bash_profile; cd $dst_path; sed -i 's/$dst_old_db_name/$dst_new_db_name/' ../config.js;"
    if (($? != 0)); then
        ./util/error.sh "$title" "update db name failed"
        exit 1
    fi
fi


#
# 更新MYSQL中的服务器列表信息
#
for id in $*; do
    if [ -z $idlist ]; then
        idlist="$id"
    else
        idlist+=","$id
    fi
done
sql="update server set merged=$dst, host='$dst_url' where id in ($idlist) OR merged in ($idlist)"
./util/info.sh "$title" "update mysql server"
result=`./mysql/query.sh "login" "$sql"`
if [ -z $result ]; then
    ./util/error.sh "$title" "update mysql server failed"
    exit 1
fi

#
# 启动合服后的目标服务器
#
./game online $dst
if (($? != 0)); then
    ./util/error.sh "$title" "online failed"
    exit 1
fi
sleep 1

./util/info.sh "$title" "OK"

